﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Googler.DAL;
using System.IO;
using System.Diagnostics;
using HodhodNews.Storage;
using Googler.BLL;
using System.Web;

namespace HodhodNews.Aggregation
{
    public class MulibleSourcesNewsAggregationProvider : NewsAggregationProvider
    {

        List<Keyword> Keywords
        {
            get;
            set;
        }
        List<News> _NewsList;
        public List<News> NewsList
        {
            get
            {
                return _NewsList;
            }
            set
            {
                _NewsList = value;
            }
        }


        /// <summary>
        /// Aggregate and saves news from mulible sources
        /// </summary>
        /// <param name="options"></param>
        /// <returns></returns>
        public override List<News> Aggregate(AggregationOptions options)
        {
            Sessions.NotificationMessages.Add(new NotificationMessage()
            {
                Text = "AGGREGATION STARTED " + DateTime.Now.ToShortTimeString()
            });

            this.Keywords = options.Keywords;

            using (new TimeLogger("Google news aggregator", 1))
            {
                NewsList = new GoogleAtomNewsAggregationProvider().Aggregate(new AggregationOptions()
                {
                    Keywords = this.Keywords
                });
                Sessions.NotificationMessages.Add(new NotificationMessage()
                {
                    Text = "Google News Count " + NewsList.Count,
                    Ident = 1
                });
            }
            using (new TimeLogger("Yahoo news aggregator", 1))
            {
                try
                {
                    var yahooList = new YahooNewsAggregationProvider().Aggregate(new AggregationOptions()
                    {
                        Keywords = this.Keywords
                    });
                    Sessions.NotificationMessages.Add(new NotificationMessage()
                    {
                        Text = "Yahoo News Count " + yahooList.Count,
                        Ident = 1
                    });
                    NewsList = yahooList.Union(NewsList).ToList();
                }
                catch
                {
                }
            }


            using (new TimeLogger("Saving news ", 1))
            {
                StorageProvider.Insance.Save(NewsList);
            }


            StorageProvider.Insance.UpdateStatistics();
            DoSomeLoggingStuff();

            Sessions.NotificationMessages.Add(new NotificationMessage()
            {
                Text = "AGGREGATION FINISHED " + DateTime.Now.ToShortTimeString()
            });

            return NewsList;
        }
        private void DoSomeLoggingStuff()
        {
            var context = new DataContext();
            var appSetting = context.AppSettings.Where(aps => aps.Key == "AggregationLastUpdate").FirstOrDefault();
            if (appSetting != null)
            {
                appSetting.Value = DateTime.Now.ToString();
                Sessions.AggregationLastUpdate = Convert.ToDateTime(appSetting.Value);
                context.SaveChanges();
            }

            Debug.WriteLine("Writing to file...");

            try
            {


                using (StreamWriter writer = new StreamWriter(Consts.AggregationLogFilePath, true))
                {
                    writer.WriteLine("Aggregated {0} News Item from: {1}", NewsList.Count, DateTime.Now);

                    writer.Close();
                }
            }
            catch (Exception x)
            {
                Debug.WriteLine(x);
            }

            Debug.WriteLine("File write successful");
        }

    }
}
